from flask import Flask, render_template, request, jsonify, redirect, url_for, session, flash
from models import db, User, Elderly, HealthRecord, HealthAdvice
from config import Config
from functools import wraps


app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/')
@login_required
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        print(f"尝试登录: 用户名={username}")
        
        user = User.query.filter_by(username=username).first()
        
        if user is None:
            flash('用户名不存在')
            return redirect(url_for('login'))
        
        if not user.check_password(password):
            flash('密码错误')
            return redirect(url_for('login'))
        
        session['user_id'] = user.id
        return redirect(url_for('index'))
    
    return render_template('login.html')

@app.route('/logout')
def logout():
    session.pop('user_id', None)
    return redirect(url_for('login'))

@app.route('/api/elderly', methods=['GET', 'POST'])
@login_required
def elderly_api():
    if request.method == 'POST':
        data = request.json
        elderly = Elderly(
            name=data['name'],
            gender=data['gender'],
            birth_date=data['birth_date'],
            phone=data['phone'],
            address=data['address'],
            emergency_contact=data['emergency_contact'],
            emergency_phone=data['emergency_phone']
        )
        db.session.add(elderly)
        db.session.commit()
        return jsonify({'message': '添加成功'})
    else:
        elderly_list = Elderly.query.all()
        return jsonify([{
            'id': e.id,
            'name': e.name,
            'gender': e.gender,
            'birth_date': e.birth_date.strftime('%Y-%m-%d'),
            'phone': e.phone
        } for e in elderly_list])

@app.route('/api/elderly/<int:elderly_id>', methods=['DELETE'])
@login_required
def delete_elderly(elderly_id):
    try:
        # 首先删除相关的健康记录健康建议
        HealthRecord.query.filter_by(elderly_id=elderly_id).delete()
        HealthAdvice.query.filter_by(elderly_id=elderly_id).delete()
        
        # 删除老年人档案
        elderly = Elderly.query.get_or_404(elderly_id)
        db.session.delete(elderly)
        db.session.commit()
        
        return jsonify({'message': '删除成功', 'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': str(e), 'success': False}), 400

@app.route('/api/health_record', methods=['GET', 'POST'])
@login_required
def health_record_api():
    if request.method == 'POST':
        try:
            data = request.json
            record = HealthRecord(
                elderly_id=data['elderly_id'],
                record_type=data['record_type'],
                record_date=data['record_date'],
                description=data['description'],
                doctor_advice=data.get('doctor_advice', ''),
                indicators=data['indicators']
            )
            record.health_status = record.evaluate_health_status()
            db.session.add(record)
            db.session.commit()
            return jsonify({'message': '记录添加成功', 'success': True})
        except Exception as e:
            db.session.rollback()
            return jsonify({'message': str(e), 'success': False}), 400
    else:
        elderly_id = request.args.get('elderly_id')
        if elderly_id:
            records = HealthRecord.query.filter_by(elderly_id=elderly_id).order_by(HealthRecord.record_date.desc()).all()
        else:
            records = HealthRecord.query.order_by(HealthRecord.record_date.desc()).all()
        return jsonify([{
            'id': r.id,
            'elderly_id': r.elderly_id,
            'elderly_name': r.elderly.name,
            'record_type': r.record_type,
            'record_date': r.record_date.strftime('%Y-%m-%d %H:%M'),
            'description': r.description,
            'doctor_advice': r.doctor_advice,
            'indicators': r.indicators,
            'health_status': r.health_status
        } for r in records])

@app.route('/api/health_advice', methods=['GET', 'POST'])
@login_required
def health_advice_api():
    if request.method == 'POST':
        data = request.json
        advice = HealthAdvice(
            elderly_id=data['elderly_id'],
            advice_type=data['advice_type'],
            content=data['content']
        )
        db.session.add(advice)
        db.session.commit()
        return jsonify({'message': '建议添加成功'})
    else:
        elderly_id = request.args.get('elderly_id')
        # 获取用户最新的健康记录
        latest_record = HealthRecord.query.filter_by(elderly_id=elderly_id).order_by(HealthRecord.record_date.desc()).first()
        
        if not latest_record:
            return jsonify([])
        
        # 根据健康状态生成建议
        advice_list = HealthAdvice.generate_advice(latest_record)
        
        return jsonify([{
            'advice_type': advice['type'],
            'content': advice['content'],
            'created_at': latest_record.record_date.strftime('%Y-%m-%d %H:%M'),
            'health_status': latest_record.health_status
        } for advice in advice_list])

@app.route('/api/elderly/<int:elderly_id>', methods=['PUT'])
@login_required
def update_elderly(elderly_id):
    try:
        elderly = Elderly.query.get_or_404(elderly_id)
        data = request.json
        
        # 更新老年人信息
        elderly.name = data['name']
        elderly.gender = data['gender']
        elderly.birth_date = data['birth_date']
        elderly.phone = data['phone']
        elderly.address = data['address']
        elderly.emergency_contact = data['emergency_contact']
        elderly.emergency_phone = data['emergency_phone']
        
        db.session.commit()
        return jsonify({'message': '修改成功', 'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': str(e), 'success': False}), 400

# 获取单个老年人详细信息
@app.route('/api/elderly/<int:elderly_id>', methods=['GET'])
@login_required
def get_elderly(elderly_id):
    elderly = Elderly.query.get_or_404(elderly_id)
    return jsonify({
        'id': elderly.id,
        'name': elderly.name,
        'gender': elderly.gender,
        'birth_date': elderly.birth_date.strftime('%Y-%m-%d'),
        'phone': elderly.phone,
        'address': elderly.address,
        'emergency_contact': elderly.emergency_contact,
        'emergency_phone': elderly.emergency_phone
    })

@app.route('/elderly-management')
@login_required
def elderly_management():
    return render_template('elderly_management.html')

@app.route('/health-record')
@login_required
def health_record():
    return render_template('health_record.html')

@app.route('/health-advice')
@login_required
def health_advice():
    return render_template('health_advice.html')

if __name__ == '__main__':
    app.run(debug=True) 